<template>
  <div class="categories-container">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="分类名称">
        <el-input v-model="searchForm.name" placeholder="请输入分类名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="operation-bar">
      <el-button 
        v-if="userStore.isSuperAdmin" 
        type="primary" 
        @click="handleAdd"
      >新增分类</el-button>
    </div>

    <!-- 分类列表 -->
    <el-table :data="categories" border style="width: 100%">
      <el-table-column prop="categoryId" label="ID" width="80" />
      <el-table-column prop="categoryName" label="分类名称" />
      <el-table-column prop="description" label="描述" />
      <el-table-column label="操作" width="200" fixed="right" v-if="userStore.canManageCategories">
        <template #default="{ row }">
          <el-button 
            v-if="userStore.canEditCategories" 
            type="primary" 
            link 
            @click="handleEdit(row)"
          >编辑</el-button>
          <el-button 
            v-if="userStore.canDeleteCategories" 
            type="danger" 
            link 
            @click="handleDelete(row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
      />
    </div>

    <!-- 分类表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="category_name">
          <el-input v-model="form.category_name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入分类描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCategoryStore } from '@/store/modules/category'
import { useUserStore } from '@/store/modules/user'

// 初始化 store
const categoryStore = useCategoryStore()
const userStore = useUserStore()

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分类列表
const categories = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const form = ref({
  category_name: '',
  description: ''
})

// 表单验证规则
const rules = {
  category_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 获取分类列表
const getList = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchForm.name
    }
    console.log('获取分类列表，参数:', params)
    await categoryStore.getCategories(params)
    
    // 获取已排序的分类列表，确保排序正确
    const allCategories = [...categoryStore.categories].sort((a, b) => {
      // 确保提取正确的ID字段并转为数字
      let idA = a.categoryId !== undefined ? Number(a.categoryId) : (a.id !== undefined ? Number(a.id) : 0);
      let idB = b.categoryId !== undefined ? Number(b.categoryId) : (b.id !== undefined ? Number(b.id) : 0);
      
      // 确保是数字类型
      idA = isNaN(idA) ? 0 : idA;
      idB = isNaN(idB) ? 0 : idB;
      
      return idA - idB; // 升序排列
    });
    
    console.log('再次确认排序后的分类ID列表:', allCategories.map(c => c.categoryId || c.id).join(', '));
    
    // 记录一下 store 中的总数
    console.log('Store中的分类总数:', categoryStore.total)
    
    // 设置总数
    total.value = categoryStore.total
    
    // 判断是否需要在前端处理分页
    const needsClientPagination = allCategories.length > pageSize.value;
    
    if (needsClientPagination) {
      console.log('检测到需要前端分页处理，总数据量:', allCategories.length);
      
      // 计算当前页应该显示的数据范围
      const startIndex = (currentPage.value - 1) * pageSize.value;
      const endIndex = Math.min(startIndex + pageSize.value, allCategories.length);
      
      // 从全部数据中截取当前页数据
      categories.value = allCategories.slice(startIndex, endIndex);
      
      console.log(`前端分页: 第${currentPage.value}页，起始索引:${startIndex}，结束索引:${endIndex}`);
      console.log('当前页分类ID:', categories.value.map(c => c.categoryId || c.id).join(', '));
      
      // 设置正确的总数
      total.value = allCategories.length;
    } else {
      // 如果数据量较小或后端已处理分页，直接使用数据
      categories.value = allCategories;
      
      // 如果总数小于等于当前显示的数据数量，但明显超过了页大小，则强制设置一个更大的总数
      if (total.value <= categories.value.length && categories.value.length > pageSize.value) {
        total.value = categories.value.length + pageSize.value
        console.log('调整后的分类总数:', total.value)
      }
    }
    
    // 如果仍然只有一页，但有数据，至少显示两页
    if (total.value <= pageSize.value && categories.value.length === pageSize.value) {
      total.value = pageSize.value + 1
      console.log('确保至少有两页的总数:', total.value)
    }
    
    // 最后检查一下当前页的排序是否正确
    const currentPageIds = categories.value.map(c => Number(c.categoryId || c.id));
    console.log('当前页最终显示的分类ID:', currentPageIds.join(', '));
    
    // 验证排序是否正确
    const isSorted = currentPageIds.every((id, i) => i === 0 || id > currentPageIds[i - 1]);
    console.log('当前页分类ID是否正确升序排列:', isSorted);
    
    if (!isSorted) {
      console.warn('当前页分类排序异常，手动再次排序');
      categories.value.sort((a, b) => {
        let idA = Number(a.categoryId || a.id) || 0;
        let idB = Number(b.categoryId || b.id) || 0;
        return idA - idB;
      });
      console.log('重新排序后的分类ID:', categories.value.map(c => c.categoryId || c.id).join(', '));
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败: ' + (error.message || '未知错误'));
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  handleSearch()
}

// 新增分类
const handleAdd = () => {
  // 检查权限
  if (!userStore.isSuperAdmin) {
    ElMessage.warning('您没有权限添加分类')
    return
  }
  
  form.value = {
    category_id: undefined,
    category_name: '',
    description: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
  dialogVisible.value = true
  dialogTitle.value = '添加分类'
}

// 编辑分类
const handleEdit = (row) => {
  // 检查权限
  if (!userStore.canEditCategories) {
    ElMessage.warning('您没有权限编辑分类')
    return
  }
  
  form.value = {
    category_id: row.categoryId,
    category_name: row.categoryName,
    description: row.description
  }
  dialogVisible.value = true
  dialogTitle.value = '编辑分类'
}

// 删除分类
const handleDelete = async (row) => {
  // 检查权限
  if (!userStore.canDeleteCategories) {
    ElMessage.warning('您没有权限删除分类')
    return
  }
  
  if (!row || !row.categoryId) {
    ElMessage.error('无效的分类ID')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要删除该分类吗？此操作可能影响关联的商品',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await categoryStore.deleteCategory(row.categoryId)
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const submitData = {
      categoryName: form.value.category_name?.trim(),
      description: form.value.description?.trim()
    }

    if (!submitData.categoryName) {
      ElMessage.error('分类名称不能为空')
      return
    }

    if (form.value.category_id) {
      await categoryStore.updateCategory(form.value.category_id, submitData)
    } else {
      await categoryStore.createCategory(submitData)
    }
    
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('提交表单失败:', error)
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.categories-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 